require('../../../utils/formData.js'); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    beforeImgSrc: '', 
    afterImgSrc: '',  
    reportList: null,
    clicked: false,
    details: {
      cleanliness_score: 1,
      assessment_result: '',
      change_area_ratio: 0
    }
  },
  getTokenData() {
    try {
      const tokenData = wx.getStorageSync('auth_token');
      if (tokenData && Date.now() < tokenData.expireTime) {
        return tokenData;
      } else {
        return null;
      }
    } catch (e) {
      console.error('获取 Token 失败', e);
      return null;
    }
  },
  getRequestHeader() {
    const tokenData = this.getTokenData();
    const headers = {
      'Content-Type': 'application/json'
    };
    if (tokenData) {
      headers[tokenData.tokenName] = tokenData.tokenValue;
      console.log('请求头:', headers);
    }
    return headers;
  },
  handleSelectImage(e) {
    const type = e.currentTarget.dataset.type; 
    const that = this;
    this.setData({
      clicked: true
    })
    wx.chooseImage({
      count: 1, 
      sizeType: ['compressed'], 
      sourceType: ['album', 'camera'], 
      success(res) {
        const tempFilePaths = res.tempFilePaths; 
        if (type === 'before') {
          that.setData({beforeImgSrc: tempFilePaths[0]});
        } else {
          that.setData({afterImgSrc: tempFilePaths[0]});
        }
        if (that.data.beforeImgSrc && that.data.afterImgSrc) {
          that.uploadBothImages();
        }
      }
    });
  },
  uploadBothImages() {
    const header = this.getRequestHeader()
    const { beforeImgSrc, afterImgSrc } = this.data;
    if (!beforeImgSrc || !afterImgSrc) return;
    const boundary = '----WebKitFormBoundary' + Math.random().toString(36).substr(2);
    let formData = '';
    formData += `--${boundary}\r\n`;
    formData += `Content-Disposition: form-data; name="beforeImage"; filename="before.jpg"\r\n`;
    formData += `Content-Type: image/jpeg\r\n\r\n`;
    formData += `--${boundary}\r\n`;
    formData += `Content-Disposition: form-data; name="afterImage"; filename="after.jpg"\r\n`;
    formData += `Content-Type: image/jpeg\r\n\r\n`;
    formData += `--${boundary}--\r\n`;
    const fs = wx.getFileSystemManager();
    const beforeBuffer = fs.readFileSync(beforeImgSrc, 'binary');
    const afterBuffer = fs.readFileSync(afterImgSrc, 'binary');
    wx.request({
      url: 'https://ufhmfcbjuwjt.sealoshzh.site/api/analyze',
      method: 'POST',
      header: header,
      data: formData, 
      success: (res) => {
        console.log('上传成功', res);
        this.setData({
          details: res.data
        })
        wx.showToast({ title: '上传成功', icon: 'success' });
      },
      fail: (err) => {
        console.error('上传失败', err);
        wx.showToast({ title: '上传失败', icon: 'none' });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})